package cc.rengu.igas.momp.core.service.trans;

import cc.rengu.igas.momp.common.constant.CommonConstant;
import cc.rengu.igas.momp.common.dao.*;
import cc.rengu.igas.momp.common.dao.impl.*;
import cc.rengu.igas.momp.common.entity.*;
import cc.rengu.igas.momp.common.enums.*;
import cc.rengu.igas.momp.common.util.CommonMessageCheck;
import cc.rengu.igas.momp.common.util.JsonOperation;
import cc.rengu.igas.momp.common.util.MompAmountUtil;
import cc.rengu.igas.momp.facade.bean.AgentProfitSharingMcInfoBean;
import cc.rengu.igas.momp.facade.bean.AgentProfitSharingRuleInfoBean;
import cc.rengu.igas.momp.facade.bean.McOrgInfoBean;
import cc.rengu.igas.momp.facade.request.EditAgentProfitSharingMcDetailRequest;
import cc.rengu.igas.momp.facade.response.EditAgentProfitSharingMcDetailResponse;
import cc.rengu.oltp.service.base.RadpService;
import cc.rengu.oltp.service.common.constant.AppConfigConstant;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.enums.ChannelEnum;
import cc.rengu.oltp.service.common.enums.OltpRpcdEnum;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.utility.util.ConvertUtil;
import cc.rengu.oltp.utility.util.DbsUtil;
import cc.rengu.oltp.utility.util.XmlConfigUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;
import cc.rengu.utility.base.StringUtil;
import cc.rengu.utility.dbs.Database;

import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 代理商分润类活动信息编辑功能实现
 *
 * @author Jinan Liu
 * @version 1.0.0
 * @date 2020/4/1 10:59
 */
public class EditAgentProfitSharingMcDetailInfoService extends RadpService {

    private String globalInstId;
    private String globalMcNo;
    private String globalTimeStamp;
    private String globalOprId;
    private String globalTxnDate;
    private final static String TABLE_NAME = TableNameEnum.T_M_MC_APS_INFO.getTableNameCode();
    private String globalOrgId;
    private BigDecimal zero = BigDecimal.ZERO;

    @Override
    protected int bizInit(String s) {
        return CommonConstant.PROCESS_SUCCESS;
    }

    @Override
    protected int bizProcess(String s, int i) {

        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();

        try {

            EditAgentProfitSharingMcDetailRequest editAgentProfitSharingMcDetailRequest = new EditAgentProfitSharingMcDetailRequest();
            ConvertUtil.convertOutput(editAgentProfitSharingMcDetailRequest);

            EditAgentProfitSharingMcDetailResponse editAgentProfitSharingMcDetailResponse = new EditAgentProfitSharingMcDetailResponse();
            editAgentProfitSharingMcDetailResponse.setHeader(editAgentProfitSharingMcDetailRequest.getHeader());
            BizResponse<EditAgentProfitSharingMcDetailResponse> bizResponse = new BizResponse<>();
            bizResponse.setResult(editAgentProfitSharingMcDetailResponse);

            /* 判断查询类型 */
            rglog.debug("TXN_NUM=<{}>", editAgentProfitSharingMcDetailRequest.getHeader().getTxnNum());

            globalInstId = editAgentProfitSharingMcDetailRequest.getHeader().getInstId();
            globalTimeStamp = new SimpleDateFormat(CommonConstant.TIMESTAMP_FORMAT).format(new Date());
            globalOprId = editAgentProfitSharingMcDetailRequest.getQueryId();
            globalTxnDate = editAgentProfitSharingMcDetailRequest.getHeader().getTransDate();
            globalOrgId = editAgentProfitSharingMcDetailRequest.getQueryOrgId();

            String queryType = editAgentProfitSharingMcDetailRequest.getQueryType();
            String queryRole = editAgentProfitSharingMcDetailRequest.getQueryRole();
            String oprType = editAgentProfitSharingMcDetailRequest.getOprType();

            rglog.debug("QUERY_TYPE=<{}>", queryType);
            rglog.debug("QUERY_ID=<{}>", globalOprId);
            rglog.debug("QUERY_ROLE=<{}>", queryRole);
            rglog.debug("OPR_TYPE=<{}>", oprType);

            /* 报文检查 */
            CommonMessageCheck.checkBizMessageHeader(queryType, globalOprId, queryRole, rglog);
            CommonMessageCheck.checkSingleValue(oprType, rglog);

            if (!StringUtil.isNullorEmpty(editAgentProfitSharingMcDetailRequest.getMcInfoObj().getMcNo())) {
                globalMcNo = editAgentProfitSharingMcDetailRequest.getMcInfoObj().getMcNo();
            }

            //判断上送的机构信息和代理商所属机构是否匹配
            checkAgentAndOrgInfo(editAgentProfitSharingMcDetailRequest);

            // 服务调用
            BizResponse<EditAgentProfitSharingMcDetailResponse> bizResponseNew = editAgentProfitSharingMcDetailInfo(
                    editAgentProfitSharingMcDetailRequest, editAgentProfitSharingMcDetailResponse, xmlTreeUtil);

            ConvertUtil.convertInput(bizResponseNew.getResult());

        } catch (BizException e) {
            try {
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_CODE, e.getCode());
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_DESC, e.getMessage());
                xmlTreeUtil.setXmlTreeStringValue(CommonConstant.KEY_RESPDESC, e.getMessage());
            } catch (Exception e1) {
                rglog.error(StringUtil.ExceptionToString(e1));
            }
        } catch (Exception e) {
            rglog.error(StringUtil.ExceptionToString(e));
            try {
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_CODE, OltpRpcdEnum.OLTP_PROCESS_ERROR.getRespCode());
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_DESC, OltpRpcdEnum.OLTP_PROCESS_ERROR.getRespDesc());
                xmlTreeUtil.setXmlTreeStringValue(CommonConstant.KEY_RESPDESC, e.getMessage());
            } catch (Exception e1) {
                rglog.error(StringUtil.ExceptionToString(e));
            }
        }

        return CommonConstant.PROCESS_SUCCESS;
    }

    @Override
    protected int bizTerminate(String s) {
        return CommonConstant.PROCESS_SUCCESS;
    }

    /**
     * 代理商分润类营销活动编辑方法
     *
     * @param editAgentProfitSharingMcDetailRequest  代理商分润类营销活动信息编辑接口请求对象
     * @param editAgentProfitSharingMcDetailResponse 代理商分润类营销活动信息编辑接口应答对象
     * @param xmlTreeUtil                            内部XML树
     * @return cc.rengu.oltp.service.model.BizResponse<cc.rengu.igas.momp.facade.response.EditMoneyOffMcDetailResponse> 代理商分润类营销活动信息编辑接口应答对象
     * @throws BizException 异常信息
     * @author Jinan Liu
     * @date 2020/5/21 18:15
     */

    private BizResponse<EditAgentProfitSharingMcDetailResponse> editAgentProfitSharingMcDetailInfo(EditAgentProfitSharingMcDetailRequest editAgentProfitSharingMcDetailRequest, EditAgentProfitSharingMcDetailResponse editAgentProfitSharingMcDetailResponse, XmlTreeUtil xmlTreeUtil)
            throws Exception {

        BizResponse<EditAgentProfitSharingMcDetailResponse> bizResponse = new BizResponse<>();

        /* 判断查询类型 */
        String queryType = editAgentProfitSharingMcDetailRequest.getQueryType();
        String queryRole = editAgentProfitSharingMcDetailRequest.getQueryRole();
        String oprType = editAgentProfitSharingMcDetailRequest.getOprType();

        /* 判断用户的角色和权限 */
        if (QueryTypeEnum.BANK_QUERY_TYPE.getQueryTypeCode().equals(queryType)) {

            if (QueryRoleEnum.BANK_BASIC_QUERY_ROLE.getQueryRoleCode().equals(queryRole)) {
                /* 银行人员录入岗-正式表和临时表所有数据 */
                rglog.info("银行人员录入岗开始操作");
                if (OprTypeEnum.EDIT_SAVE.getOprTypeCode().equals(oprType)) {

                    /* 保存数据是完全新增数据的流程，需要生成营销活动编号 */
                    if (StringUtil.isNullorEmpty(globalMcNo)) {
                        rglog.info("全新保存数据流程开始");
                        /* 如果营销活动编号不存在，说明是全新的营销活动，需要生成一个营销活动编号，并新增全部数据； */
                        globalMcNo = generateNewMcNo(editAgentProfitSharingMcDetailRequest.getMcInfoObj());
                        if (!StringUtil.isNullorEmpty(globalMcNo)) {
                            rglog.info("新生成的营销活动编号 MC_NO=<{}>", globalMcNo);
                        }

                        /* 开启数据库事务 */
                        String dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(AppConfigConstant.DATABASE_CONF_NODE, AppConfigConstant.MOMP_POOL_NAME);
                        String corporation = xmlTreeUtil.getXmlTreeStringValue(AppParamConstant.CORPORATION);
                        if (null != corporation && !corporation.isEmpty()) {
                            String dbPoolCashNode = corporation.trim() + AppParamConstant.DATABASE_CONF_NODE;
                            dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(dbPoolCashNode, AppConfigConstant.MOMP_POOL_NAME);
                        }
                        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
                        dbsUtil.dbsBeginTransaction();

                        /* 全部新增流程，插入数据 */
                        insertAllMcInfoByBank(dbsUtil, editAgentProfitSharingMcDetailRequest);
                        /* 正常结束数据库事务 */
                        dbsUtil.dbsEndTransaction(true);

                    } else {
                        rglog.info("营销活动已存在,再次保存数据流程开始");
                        /* 如果营销活动编号存在,需要根据当前数据库各状态判断是否可以更新数据 */
                        saveAllMcInfoByBank(xmlTreeUtil, editAgentProfitSharingMcDetailRequest);
                    }
                    rglog.info("保存数据流程结束");
                } else if (OprTypeEnum.EDIT_SUBMIT.getOprTypeCode().equals(oprType)) {

                    rglog.info("提交审批流程开始");
                    /* 提交审批 */
                    submitMcInfo(editAgentProfitSharingMcDetailRequest);
                    rglog.info("提交审批流程结束");

                } else if (OprTypeEnum.EDIT_DRAFT.getOprTypeCode().equals(oprType)) {
                    rglog.info("修改草稿流程开始");
                    /* 修改草稿 */
                    updateAllDraftMcInfoByBank(xmlTreeUtil, editAgentProfitSharingMcDetailRequest);
                    rglog.info("修改草稿流程结束");
                } else {
                    rglog.error("当前<{}>角色的查询用户<{}>无权限查看数据!", queryRole, queryType);
                    throw new BizException(RespCodeEnum.NOT_SUPPORTED_OPR_TYPE_ERROR.getRespCode(), RespCodeEnum.NOT_SUPPORTED_OPR_TYPE_ERROR.getRespDesc());
                }

            } else {
                /* 银行审批岗或银行发布岗 */
                rglog.error("当前<{}>角色的查询用户<{}>无权限查看数据!", queryRole, queryType);
                throw new BizException(RespCodeEnum.NO_AUTHORIZATION_TO_QUERY_ERROR.getRespCode(), RespCodeEnum.NO_AUTHORIZATION_TO_QUERY_ERROR.getRespDesc());
            }
        } else {
            /* 商户、代理商、收银员或用户 */
            rglog.error("当前<{}>角色的查询用户<{}>无权限查看数据!", queryRole, queryType);
            throw new BizException(RespCodeEnum.NO_AUTHORIZATION_TO_QUERY_ERROR.getRespCode(), RespCodeEnum.NO_AUTHORIZATION_TO_QUERY_ERROR.getRespDesc());
        }

        bizResponse.setRspSysId(ChannelEnum.MOMP.getChannelType());
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());

        editAgentProfitSharingMcDetailResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        editAgentProfitSharingMcDetailResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        editAgentProfitSharingMcDetailResponse.setMcNo(globalMcNo);
        bizResponse.setResult(editAgentProfitSharingMcDetailResponse);

        return bizResponse;
    }

    /**
     * 营销活动信息数据库实体类和接口实体类数据转换
     *
     * @param agentProfitSharingMcInfoBean 代理商分润类活动基本信息对象
     * @return cc.rengu.igas.momp.common.entity.TMMcMoneyOffInfo 代理商分润类营销活动信息表
     * @author Jinan Liu
     * @date 2020/5/21 15:18
     */
    private TMMcAgentProfitSharingInfo convertMcInfo(AgentProfitSharingMcInfoBean agentProfitSharingMcInfoBean, List<TMMcOrgInfo> mcOrgInfoList) {
        // 检查上传字段 不能为负数
        checkMcInfoObjFieldHasNegativeNumber(agentProfitSharingMcInfoBean);

        TMMcAgentProfitSharingInfo mcAgentProfitSharingInfo = new TMMcAgentProfitSharingInfo();
        try {
            /* 机构编码 */
            mcAgentProfitSharingInfo.setInstId(agentProfitSharingMcInfoBean.getInstId());
            /* 营销活动编号 */
            mcAgentProfitSharingInfo.setMcNo(globalMcNo);
            /* 营销活动名称 */
            if (StringUtil.isNullorEmpty(agentProfitSharingMcInfoBean.getMcName())) {
                throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
            } else {
                mcAgentProfitSharingInfo.setMcName(agentProfitSharingMcInfoBean.getMcName());
            }
            /* 营销活动类型 */
            if (StringUtil.isNullorEmpty(agentProfitSharingMcInfoBean.getMcType())) {
                throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
            } else {
                mcAgentProfitSharingInfo.setMcType(agentProfitSharingMcInfoBean.getMcType());
            }
            /* 营销活动状态 */
            if (StringUtil.isNullorEmpty(agentProfitSharingMcInfoBean.getMcStatus())) {
                throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
            } else {
                mcAgentProfitSharingInfo.setMcStatus(agentProfitSharingMcInfoBean.getMcStatus());
            }
            /* 活动起始日期 */
            if (StringUtil.isNullorEmpty(agentProfitSharingMcInfoBean.getMcStartDate())) {
                throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
            } else {
                mcAgentProfitSharingInfo.setMcStartDate(agentProfitSharingMcInfoBean.getMcStartDate());
            }
            /* 活动截止日期 */
            if (StringUtil.isNullorEmpty(agentProfitSharingMcInfoBean.getMcEndDate())) {
                throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
            } else {
                mcAgentProfitSharingInfo.setMcEndDate(agentProfitSharingMcInfoBean.getMcEndDate());
            }
            /* 活动结束日期 */
            if (StringUtil.isNullorEmpty(agentProfitSharingMcInfoBean.getMcActualEndDate())) {
                /* 不需要计算，直接使用活动结束日期*/
                mcAgentProfitSharingInfo.setMcActualEndDate(agentProfitSharingMcInfoBean.getMcEndDate());
            } else {
                /* 不需要计算，直接使用接口上送内容 */
                mcAgentProfitSharingInfo.setMcActualEndDate(agentProfitSharingMcInfoBean.getMcActualEndDate());
            }
            /* 机构编号 */
            mcAgentProfitSharingInfo.setOrgId(mcOrgInfoList.get(mcOrgInfoList.size() - 1).getInstId());
            /* 代理商编号 */
            if (StringUtil.isNullorEmpty(agentProfitSharingMcInfoBean.getAgentMchntNo())) {
                throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
            } else {
                mcAgentProfitSharingInfo.setAgentMchntNo(agentProfitSharingMcInfoBean.getAgentMchntNo());
            }
            /* 优惠打款模式 */
            if (StringUtil.isNullorEmpty(agentProfitSharingMcInfoBean.getDiscountTransferMode())) {
                throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
            } else {
                mcAgentProfitSharingInfo.setDiscountTransferMode(agentProfitSharingMcInfoBean.getDiscountTransferMode());
            }
            /* 活动预算 */
            if (StringUtil.isNullorEmpty(agentProfitSharingMcInfoBean.getBudget())) {
                mcAgentProfitSharingInfo.setBudget(CommonConstant.ZERO_AMOUNT);
            } else {
                mcAgentProfitSharingInfo.setBudget(MompAmountUtil.getTwoDecimal(agentProfitSharingMcInfoBean.getBudget()));
            }
            /* 达标条件 */
            if (StringUtil.isNullorEmpty(agentProfitSharingMcInfoBean.getCriteriaFlag())) {
                throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
            } else {
                mcAgentProfitSharingInfo.setCriteriaFlag(agentProfitSharingMcInfoBean.getCriteriaFlag());
            }
            /* 有效交易达标金额 */
            if (StringUtil.isNullorEmpty(agentProfitSharingMcInfoBean.getCriteriaLimit())) {
                throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
            } else {
                mcAgentProfitSharingInfo.setCriteriaLimit(MompAmountUtil.getTwoDecimal(agentProfitSharingMcInfoBean.getCriteriaLimit()));
            }
            /* 统计周期 */
            if (StringUtil.isNullorEmpty(agentProfitSharingMcInfoBean.getStatPeriod())) {
                throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
            } else {
                mcAgentProfitSharingInfo.setStatPeriod(agentProfitSharingMcInfoBean.getStatPeriod());
            }
            /* 新商户达标交易金额 */
            if (StringUtil.isNullorEmpty(agentProfitSharingMcInfoBean.getCriteriaAmount())) {
                mcAgentProfitSharingInfo.setCriteriaAmount(CommonConstant.ZERO_AMOUNT);
            } else {
                mcAgentProfitSharingInfo.setCriteriaAmount(MompAmountUtil.getTwoDecimal(agentProfitSharingMcInfoBean.getCriteriaAmount()));
            }
            /* 新商户达标交易笔数 */
            if (StringUtil.isNullorEmpty(agentProfitSharingMcInfoBean.getCriteriaQuantity())) {
                mcAgentProfitSharingInfo.setCriteriaQuantity(CommonConstant.ZERO_COMMON_CONSTANT);
            } else {
                mcAgentProfitSharingInfo.setCriteriaQuantity(agentProfitSharingMcInfoBean.getCriteriaQuantity());
            }
            /* 返现周期 */
            mcAgentProfitSharingInfo.setCashbackPeriod(CommonConstant.ZERO_COMMON_CONSTANT);

            /* 审批状态-待提交审批状态 */
            mcAgentProfitSharingInfo.setAuditStatus(AuditStatusEnum.WAIT_FOR_SUBMIT.getAuditStatusCode());
            /* 创建人 */
            mcAgentProfitSharingInfo.setOprId(globalOprId);
            /* 创建时间 */
            mcAgentProfitSharingInfo.setCreateTime(globalTimeStamp);
            /* 最后修改人 */
            if (!StringUtil.isNullorEmpty(agentProfitSharingMcInfoBean.getLastOprId())) {
                mcAgentProfitSharingInfo.setLastOprId(agentProfitSharingMcInfoBean.getLastOprId());
            }
            /* 修改时间 */
            if (!StringUtil.isNullorEmpty(agentProfitSharingMcInfoBean.getUpdateTime())) {
                mcAgentProfitSharingInfo.setUpdateTime(agentProfitSharingMcInfoBean.getUpdateTime());
            }
            /* 审批拒绝原因 */
            if (!StringUtil.isNullorEmpty(agentProfitSharingMcInfoBean.getAuditRefuseReason())) {
                mcAgentProfitSharingInfo.setAuditRefuseReason(agentProfitSharingMcInfoBean.getAuditRefuseReason());
            }
            /* 发布拒绝原因 */
            if (!StringUtil.isNullorEmpty(agentProfitSharingMcInfoBean.getPublishRefuseReason())) {
                mcAgentProfitSharingInfo.setPublishRefuseReason(agentProfitSharingMcInfoBean.getPublishRefuseReason());
            }
            /* 备用字段1 */
            if (!StringUtil.isNullorEmpty(agentProfitSharingMcInfoBean.getRemark1())) {
                mcAgentProfitSharingInfo.setRemark1(agentProfitSharingMcInfoBean.getRemark1());
            }
            /* 备用字段2 */
            if (!StringUtil.isNullorEmpty(agentProfitSharingMcInfoBean.getRemark2())) {
                mcAgentProfitSharingInfo.setRemark2(agentProfitSharingMcInfoBean.getRemark2());
            }
            /* 备用字段3 */
            if (!StringUtil.isNullorEmpty(agentProfitSharingMcInfoBean.getRemark3())) {
                mcAgentProfitSharingInfo.setRemark3(agentProfitSharingMcInfoBean.getRemark3());
            }
            /* 备用字段4 */
            if (!StringUtil.isNullorEmpty(agentProfitSharingMcInfoBean.getRemark4())) {
                mcAgentProfitSharingInfo.setRemark4(agentProfitSharingMcInfoBean.getRemark4());
            }
            /* 备用字段5 */
            if (!StringUtil.isNullorEmpty(agentProfitSharingMcInfoBean.getRemark5())) {
                mcAgentProfitSharingInfo.setRemark5(agentProfitSharingMcInfoBean.getRemark5());
            }
            /* 创建机构 */
            if (!StringUtil.isNullorEmpty(globalOrgId)) {
                mcAgentProfitSharingInfo.setCrtOrgId(globalOrgId);
            }
        } catch (Exception e) {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            e.printStackTrace(new PrintWriter(byteArrayOutputStream, true));
            rglog.error("转换营销活动信息异常,异常信息:<{}>", byteArrayOutputStream.toString());
            throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
        }

        return mcAgentProfitSharingInfo;
    }

    /**
     * 营销活动机构信息数据库实体类和接口实体类数据转换
     *
     * @param mcOrgInfoBean 营销活动机构信息对象
     * @return cc.rengu.igas.momp.common.entity.TMMcOrgInfo 营销活动机构信息表
     * @author Jinan Liu
     * @date 2020/4/1 21:11
     */
    private TMMcOrgInfo convertMcOrgInfo(McOrgInfoBean mcOrgInfoBean) {
        TMMcOrgInfo mcOrgInfo = new TMMcOrgInfo();
        try {
            /* 法人机构号 */
            mcOrgInfo.setInstId(globalInstId);
            /* 营销活动编号 */
            mcOrgInfo.setMcNo(globalMcNo);
            /* 机构编号 */
            mcOrgInfo.setOrgId(mcOrgInfoBean.getOrgId());
            /* 机构层级 */
            mcOrgInfo.setOrgHierarchy(mcOrgInfoBean.getOrgHierarchy());
            /* 机构名称 */
            mcOrgInfo.setOrgName(mcOrgInfoBean.getOrgName());
            /* 创建人 */
            mcOrgInfo.setOprId(globalOprId);
            /* 创建时间 */
            mcOrgInfo.setCreateTime(globalTimeStamp);

        } catch (Exception e) {
            rglog.error("转换营销活动机构信息异常,异常信息:<{}>", StringUtil.ExceptionToString(e));
            throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
        }

        return mcOrgInfo;
    }

    /**
     * 营销活动规则信息数据库实体类和接口实体类数据转换
     *
     * @param agentProfitSharingRuleInfoBean 代理商分润类营销活动规则信息对象
     * @return cc.rengu.igas.momp.common.entity.TMMcAgentProfitSharingRuleInfo 代理商分润类营销活动规则表
     * @author Jinan Liu
     * @date 2020/4/1 21:07
     */
    private TMMcAgentProfitSharingRuleInfo convertMcRuleInfo(AgentProfitSharingRuleInfoBean agentProfitSharingRuleInfoBean) {

        // 检查上传字段 不能为负数
        checkRuleInfoFieldHasNegativeNumber(agentProfitSharingRuleInfoBean);

        TMMcAgentProfitSharingRuleInfo mcAgentProfitSharingRuleInfo = new TMMcAgentProfitSharingRuleInfo();

        try {

            /* 法人机构号 */
            mcAgentProfitSharingRuleInfo.setInstId(globalInstId);
            /* 营销活动编号 */
            mcAgentProfitSharingRuleInfo.setMcNo(globalMcNo);
            /* 顺序号  */
            mcAgentProfitSharingRuleInfo.setRuleIndex(agentProfitSharingRuleInfoBean.getRuleIndex());
            /* 控制下限 */
            mcAgentProfitSharingRuleInfo.setCriteriaFloor(MompAmountUtil.getTwoDecimal(agentProfitSharingRuleInfoBean.getCriteriaFloor()));
            /* 控制上限 */
            mcAgentProfitSharingRuleInfo.setCriteriaCelling(MompAmountUtil.getTwoDecimal(agentProfitSharingRuleInfoBean.getCriteriaCelling()));
            /* 优惠类型 */
            mcAgentProfitSharingRuleInfo.setDiscountType(agentProfitSharingRuleInfoBean.getDiscountType());
            /* 优惠力度 */
            mcAgentProfitSharingRuleInfo.setDiscount(MompAmountUtil.getTwoDecimal(agentProfitSharingRuleInfoBean.getDiscount()));
            /* 创建人 */
            mcAgentProfitSharingRuleInfo.setOprId(globalOprId);
            /* 创建时间 */
            mcAgentProfitSharingRuleInfo.setCreateTime(globalTimeStamp);

        } catch (Exception e) {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            e.printStackTrace(new PrintWriter(byteArrayOutputStream, true));
            rglog.error("转换营销活动规则信息异常,异常信息:<{}>", byteArrayOutputStream.toString());
            throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
        }

        return mcAgentProfitSharingRuleInfo;
    }


    /**
     * 新增营销活动信息,插入正是表和临时表数据
     *
     * @param dbsUtil                               数据为操作工具类
     * @param editAgentProfitSharingMcDetailRequest 代理商分润类营销活动信息编辑接口请求对象
     * @throws Exception 异常信息
     * @author Jinan Liu
     * @date 2020/5/21 18:48
     */
    private void insertAllMcInfoByBank(DbsUtil dbsUtil, EditAgentProfitSharingMcDetailRequest editAgentProfitSharingMcDetailRequest) throws Exception {

        /* 营销活动机构信息新增 */
        List<TMMcOrgInfo> mcOrgInfoList = editAgentProfitSharingMcDetailRequest.getOrgInfoObj().stream().map(this::convertMcOrgInfo).collect(Collectors.toList());
        insertMcOrgInfo(dbsUtil, mcOrgInfoList);
        List<TMPlatBizTmp> tmpOrgList = mcOrgInfoList.stream().map(this::convertMcOrgInfoToTmp).collect(Collectors.toList());
        insertMultiMcDetialInfoByBank(dbsUtil, tmpOrgList);

        //按照机构层级排序,插入营销活动信息的时候orgId字段,取排序后的最后一个
        mcOrgInfoList.sort(Comparator.comparingInt(x -> Integer.parseInt(x.getOrgHierarchy())));

        /* 营销活动基本信息新增 */
        TMMcAgentProfitSharingInfo mcAgentProfitSharingInfo = convertMcInfo(editAgentProfitSharingMcDetailRequest.getMcInfoObj(), mcOrgInfoList);
        insertAgentProfitSharingMcInfo(dbsUtil, mcAgentProfitSharingInfo);
        TMPlatBizTmp tmPlatBizTmp = convertMoMcInfoToTmp(mcAgentProfitSharingInfo);
        insertTmpMoMcInfo(dbsUtil, tmPlatBizTmp);

        /* 营销活动规则信息新增 */
        List<TMMcAgentProfitSharingRuleInfo> mcAgentProfitSharingRuleInfoList = editAgentProfitSharingMcDetailRequest.getRuleInfoList().stream().map(this::convertMcRuleInfo).collect(Collectors.toList());
        insertMcAgentProfitSharingRuleInfo(dbsUtil, mcAgentProfitSharingRuleInfoList);
        List<TMPlatBizTmp> tmpMoMcRuleList = mcAgentProfitSharingRuleInfoList.stream().map(this::convertMoMcRuleInfoToTmp).collect(Collectors.toList());
        insertMultiMcDetialInfoByBank(dbsUtil, tmpMoMcRuleList);
    }

    /**
     * 提交营销活动信息
     *
     * @param editAgentProfitSharingMcDetailRequest 代理商分润类营销活动信息编辑接口请求对象
     * @throws Exception 异常信息
     * @author Jinan Liu
     * @date 2020/4/6 17:43
     */
    private void submitMcInfo(EditAgentProfitSharingMcDetailRequest editAgentProfitSharingMcDetailRequest) throws Exception {
        int returnCode = 0;
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();

        rglog.info("提交审批流程开始");

        /* 营销活动信息正式表查询 */
        TMMcAgentProfitSharingInfo mcAgentProfitSharingInfo = null;
        McDetailInfoMapper mcDetailInfoMapper = new McDetailInfoMapperImpl();
        /* 营销活动信息临时表查询 */
        TMPlatBizTmp platBizTmp = null;
        PlatBizTmpMapper platBizTmpMapper = new PlatBizTmpMapperImpl();

        if (StringUtil.isNullorEmpty(globalMcNo)) {
            rglog.info("上送数据无营销活动编号!");
        } else {
            mcAgentProfitSharingInfo = (TMMcAgentProfitSharingInfo) mcDetailInfoMapper.selectMcDetailInfo(globalInstId, globalMcNo, TableNameEnum.T_M_MC_APS_INFO.getTableNameCode());
            platBizTmp = platBizTmpMapper.selectTmpMcInfo(globalInstId, globalMcNo, TableNameEnum.T_M_MC_APS_INFO.getTableNameCode());
        }

        /* 开启数据库事务 */
        String dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(AppConfigConstant.DATABASE_CONF_NODE, AppConfigConstant.MOMP_POOL_NAME);
        String corporation = xmlTreeUtil.getXmlTreeStringValue(AppParamConstant.CORPORATION);
        if (null != corporation && !corporation.isEmpty()) {
            String dbPoolCashNode = corporation.trim() + AppParamConstant.DATABASE_CONF_NODE;
            dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(dbPoolCashNode, AppConfigConstant.MOMP_POOL_NAME);
        }
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        dbsUtil.dbsBeginTransaction();

        if (null == mcAgentProfitSharingInfo && null == platBizTmp) {
            /* 新增提交审批场景，新增数据后直接确认创建

             * 如果营销活动编号不存在，说明是全新的营销活动，需要生成一个营销活动编号，并新增全部数据；
             * 如果营销活动编号存在，说明是接口调用错误，需要返回失败信息；
             */
            if (StringUtil.isNullorEmpty(globalMcNo)) {
                /* 生成营销活动编号 */
                globalMcNo = generateNewMcNo(editAgentProfitSharingMcDetailRequest.getMcInfoObj());
                if (!StringUtil.isNullorEmpty(globalMcNo)) {
                    rglog.info("新生成的营销活动编号 MC_NO=<{}>", globalMcNo);
                }

                /* 全部新增流程，插入数据 */
                rglog.info("提交审批新增流程开始");
                insertAllMcInfoByBank(dbsUtil, editAgentProfitSharingMcDetailRequest);

            } else {
                /* 如果营销活动编号存在,但是上步没有查询到营销活动,错误 */
                rglog.error("当前营销活动<{}>不可保存数据!", globalMcNo);
                dbsUtil.dbsEndTransaction(false);
                throw new BizException(RespCodeEnum.NO_AVAILABLE_DATA_TO_PROCESS_ERROR.getRespCode(), RespCodeEnum.NO_AVAILABLE_DATA_TO_PROCESS_ERROR.getRespDesc());
            }

            /* 更新临时表审批状态 */
            returnCode = platBizTmpMapper.updateTmpMcAuditStatusByPrimaryKey(globalInstId, globalMcNo, AuditStatusEnum.WAIT_FOR_SUBMIT.getAuditStatusCode(), AuditStatusEnum.NEW_AUDIT_PROCESSING.getAuditStatusCode(), BizStatusEnum.TMP_STATUS.getBizStatusCode(), McStatusEnum.DRAFT.getMcStatusCode());
            if (Database.DBS_SUCCESS != returnCode) {
                /* 更新临时表中营销活动审批状态失败 */
                dbsUtil.dbsEndTransaction(false);
                rglog.error("更新临时表中营销活动审批状态失败, RETURN_CODE=<{}>, MC_NO=<{}>", returnCode, globalMcNo);
                throw new BizException(RespCodeEnum.UPDATE_TMP_MC_STATUS_FAILED_ERROR.getRespCode(), RespCodeEnum.UPDATE_TMP_MC_STATUS_FAILED_ERROR.getRespDesc());
            }

            /* 更新正式表审批状态 - T_M_MC_APS_INFO*/
            returnCode = mcDetailInfoMapper.updateAgentProfitSharingMcAuditStatusByPrimaryKey(globalInstId, globalMcNo, AuditStatusEnum.NEW_AUDIT_PROCESSING.getAuditStatusCode());
            if (Database.DBS_SUCCESS != returnCode) {
                /* 更新正式表中营销活动审批状态失败 */
                dbsUtil.dbsEndTransaction(false);
                rglog.error("更新正式表中营销活动审批状态失败, RETURN_CODE=<{}>, INST_ID=<{}>, MC_NO=<{}>", returnCode, globalInstId, globalMcNo);
                throw new BizException(RespCodeEnum.UPDATE_MC_STATUS_FAILED_ERROR.getRespCode(), RespCodeEnum.UPDATE_MC_STATUS_FAILED_ERROR.getRespDesc());
            }

            /* 正常结束数据库事务 */
            dbsUtil.dbsEndTransaction(true);

        } else if (null != mcAgentProfitSharingInfo && null != platBizTmp) {
            /* 数据库有历史数据，需要判断历史数据状态 */

            /* 判断营销活动审批状态 */
            if (!AuditStatusEnum.WAIT_FOR_SUBMIT.getAuditStatusCode().equals(platBizTmp.getAuditStatus()) &&
                    !AuditStatusEnum.NEW_AUDIT_REJECT.getAuditStatusCode().equals(platBizTmp.getAuditStatus()) &&
                    !AuditStatusEnum.MODIFY_AUDIT_REJECT.getAuditStatusCode().equals(platBizTmp.getAuditStatus()) &&
                    !AuditStatusEnum.PUBLISH_AUDIT_REJECT.getAuditStatusCode().equals(platBizTmp.getAuditStatus())) {
                /* 不可提交审批状态 */
                rglog.error("营销活动是不可提交审批状态,不可提交审批, RETURN_CODE=<{}>, MC_NO=<{}>", returnCode, globalMcNo);
                dbsUtil.dbsEndTransaction(false);
                throw new BizException(RespCodeEnum.WRONG_AUDIT_STATUS_TO_SUBMIT_ERROR.getRespCode(), RespCodeEnum.WRONG_AUDIT_STATUS_TO_SUBMIT_ERROR.getRespDesc());
            }

            /* 判断营销活动状态*/
            if (!McStatusEnum.DRAFT.getMcStatusCode().equals(platBizTmp.getMcStatus()) &&
                    !McStatusEnum.NOT_PUBLISHED.getMcStatusCode().equals(platBizTmp.getMcStatus())) {
                /* 营销活动状态异常，不可提交审批 */
                dbsUtil.dbsEndTransaction(false);
                rglog.error("营销活动状态异常，不可提交审批, MC_STATUS=<{}>, MC_NO=<{}>", platBizTmp.getMcStatus(), globalMcNo);
                throw new BizException(RespCodeEnum.WRONG_MC_STATUS_TO_SUBMIT_ERROR.getRespCode(), RespCodeEnum.WRONG_MC_STATUS_TO_SUBMIT_ERROR.getRespDesc());
            } else {
                /* 新增提交审批场景
                 * 如果营销活动编号不存在，说明数据异常，不可提交审批；
                 * 如果营销活动编号存在，说明是正常的新增提交审批场景，可以提交审批；
                 */
                if (StringUtil.isNullorEmpty(globalMcNo)) {
                    /* 全部更新流程，更新数据 */
                    rglog.error("当前营销活动<{}>不可保存数据!", globalMcNo);
                    dbsUtil.dbsEndTransaction(false);
                    throw new BizException(RespCodeEnum.NO_AVAILABLE_DATA_TO_PROCESS_ERROR.getRespCode(), RespCodeEnum.NO_AVAILABLE_DATA_TO_PROCESS_ERROR.getRespDesc());
                } else {
                    /* 正式表临时表一起更新,先删除原数据再插入 */
                    updateMcInfoByBank(dbsUtil, editAgentProfitSharingMcDetailRequest);
                }

                String tmpMcStatus = platBizTmp.getMcStatus();
                String tmpAuditStatus = platBizTmp.getAuditStatus();
                String tmpBizStatus = platBizTmp.getBizStatus();

                String mcStatus = mcAgentProfitSharingInfo.getMcStatus();

                String newTmpAuditStatus = null;
                String newAuditStatus = null;

                if (AuditStatusEnum.WAIT_FOR_SUBMIT.getAuditStatusCode().equals(tmpAuditStatus)) {
                    newTmpAuditStatus = AuditStatusEnum.NEW_AUDIT_PROCESSING.getAuditStatusCode();
                    newAuditStatus = AuditStatusEnum.NEW_AUDIT_PROCESSING.getAuditStatusCode();
                }

                if (AuditStatusEnum.NEW_AUDIT_REJECT.getAuditStatusCode().equals(platBizTmp.getAuditStatus()) ||
                        AuditStatusEnum.MODIFY_AUDIT_REJECT.getAuditStatusCode().equals(platBizTmp.getAuditStatus()) ||
                        AuditStatusEnum.PUBLISH_AUDIT_REJECT.getAuditStatusCode().equals(platBizTmp.getAuditStatus())) {
                    newTmpAuditStatus = AuditStatusEnum.MODIFY_AUDIT_PROCESSING.getAuditStatusCode();
                    newAuditStatus = AuditStatusEnum.MODIFY_AUDIT_PROCESSING.getAuditStatusCode();
                }

                /* 更新临时表审批状态 */
                returnCode = platBizTmpMapper.updateTmpMcAllStatusByMcNoAndAuditStatus(globalInstId, globalMcNo, tmpBizStatus, tmpMcStatus, newTmpAuditStatus, AuditStatusEnum.WAIT_FOR_SUBMIT.getAuditStatusCode(), globalOprId, globalTimeStamp);
                if (Database.DBS_SUCCESS != returnCode) {
                    /* 更新临时表中营销活动审批状态失败 */
                    dbsUtil.dbsEndTransaction(false);
                    rglog.error("更新临时表中营销活动审批状态失败, RETURN_CODE=<{}>, MC_NO=<{}>", returnCode, globalMcNo);
                    throw new BizException(RespCodeEnum.UPDATE_TMP_MC_STATUS_FAILED_ERROR.getRespCode(), RespCodeEnum.UPDATE_TMP_MC_STATUS_FAILED_ERROR.getRespDesc());
                }

                /* 更新正式表审批状态 */
                TMMcAgentProfitSharingInfo tmMcAgentProfitSharingInfo1 = new TMMcAgentProfitSharingInfo();
                tmMcAgentProfitSharingInfo1.setInstId(globalInstId);
                tmMcAgentProfitSharingInfo1.setMcNo(globalMcNo);
                tmMcAgentProfitSharingInfo1.setMcStatus(mcStatus);
                tmMcAgentProfitSharingInfo1.setAuditStatus(newAuditStatus);
                tmMcAgentProfitSharingInfo1.setLastOprId(globalOprId);
                tmMcAgentProfitSharingInfo1.setUpdateTime(globalTimeStamp);

                returnCode = mcDetailInfoMapper.updateMcStatusForPublishing(tmMcAgentProfitSharingInfo1, TABLE_NAME);
                if (Database.DBS_SUCCESS != returnCode) {
                    /* 更新正式表中营销活动审批状态失败 */
                    dbsUtil.dbsEndTransaction(false);
                    rglog.error("更新正式表中营销活动审批状态失败, RETURN_CODE=<{}>, MC_NO=<{}>", returnCode, globalMcNo);
                    throw new BizException(RespCodeEnum.UPDATE_MC_STATUS_FAILED_ERROR.getRespCode(), RespCodeEnum.UPDATE_MC_STATUS_FAILED_ERROR.getRespDesc());
                }
            }
            /* 正常结束数据库事务 */
            dbsUtil.dbsEndTransaction(true);

        } else {
            /* 异常结束数据库事务 */
            rglog.error("查询营销活动信息失败, RETURN_CODE=<{}>, MC_NO=<{}>", returnCode, globalMcNo);
            dbsUtil.dbsEndTransaction(false);
            throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
        }
    }

    /**
     * 更新营销活动信息
     * 修改草稿流程使用 --未有接口直接修改草稿的使用场景 add by zzj
     * 在草稿进行保存的时候也可以使用
     *
     * @param editAgentProfitSharingMcDetailRequest 代理商分润类营销活动信息编辑接口请求对象
     * @throws Exception 异常信息
     * @author Jinan Liu
     * @date 2020/4/2 00:13
     */
    private void updateAllDraftMcInfoByBank(XmlTreeUtil xmlTreeUtil, EditAgentProfitSharingMcDetailRequest editAgentProfitSharingMcDetailRequest) throws Exception {

        /* 开启数据库事务 */
        String dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(AppConfigConstant.DATABASE_CONF_NODE, AppConfigConstant.MOMP_POOL_NAME);
        String corporation = xmlTreeUtil.getXmlTreeStringValue(AppParamConstant.CORPORATION);
        if (null != corporation && !corporation.isEmpty()) {
            String dbPoolCashNode = corporation.trim() + AppParamConstant.DATABASE_CONF_NODE;
            dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(dbPoolCashNode, AppConfigConstant.MOMP_POOL_NAME);
        }
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        dbsUtil.dbsBeginTransaction();

        TMPlatBizTmp tmPlatBizTmp = new TMPlatBizTmp();
        tmPlatBizTmp.setInstId(globalInstId);
        tmPlatBizTmp.setMcNo(globalMcNo);
        tmPlatBizTmp.setOprTableEname(TableNameEnum.T_M_MC_APS_INFO.getTableNameCode());
        tmPlatBizTmp.setBizStatus(BizStatusEnum.TMP_STATUS.getBizStatusCode());
        tmPlatBizTmp.setMcStatus(McStatusEnum.DRAFT.getMcStatusCode());
        tmPlatBizTmp.setAuditStatus(AuditStatusEnum.WAIT_FOR_SUBMIT.getAuditStatusCode());

        //删除指定营销活动编号的所有草稿状态的数据
        deleteAllDraftMcInfoByBank(dbsUtil, tmPlatBizTmp);
        //删除正式表数据
        deleteAgentProfitSharingMcInfo(dbsUtil);
        deleteMcOrgInfo(dbsUtil);
        deleteAgentProfitSharingRuleInfo(dbsUtil);

        //重新插入正式表和临时表数据
        insertAllMcInfoByBank(dbsUtil, editAgentProfitSharingMcDetailRequest);

        /* 正常结束数据库事务 */
        dbsUtil.dbsEndTransaction(true);
    }

    /**
     * 生成营销活动编号
     *
     * @param agentProfitSharingMcInfoBean 代理商分润类活动基本信息对象
     * @return java.lang.String
     * @throws Exception 异常信息
     * @author Jinan Liu
     * @date 2020/5/21 14:57
     */
    private String generateNewMcNo(AgentProfitSharingMcInfoBean agentProfitSharingMcInfoBean) throws Exception {

        // MC+2位营销活动类型+银行编码(0)+8位活动起始日期+8位活动截止日期+11位sequence
        MompSequenceMapper mompSequenceMapper = new MompSequenceMapperImpl();

        String mcNoSuffix = mompSequenceMapper.getMompNextMaNoSeq();

        return "MC" + agentProfitSharingMcInfoBean.getMcType() + CommonConstant.SPONSOR_BANK + agentProfitSharingMcInfoBean.getMcStartDate() + agentProfitSharingMcInfoBean.getMcEndDate() + mcNoSuffix;
    }


    /**
     * 插入代理商分润类营销活动基本信息
     *
     * @param dbsUtil                  数据库操作工具类
     * @param mcAgentProfitSharingInfo 代理商分润类营销活动信息表
     * @throws Exception 异常信息
     * @author Jinan Liu
     * @date 2020/5/21 16:35
     */
    private void insertAgentProfitSharingMcInfo(DbsUtil dbsUtil, TMMcAgentProfitSharingInfo mcAgentProfitSharingInfo) throws Exception {

        McDetailInfoMapper mcDetailInfoMapper = new McDetailInfoMapperImpl();
        int returnCode = mcDetailInfoMapper.insertAgentProfitSharingMcInfo(null, mcAgentProfitSharingInfo);
        if (Database.DBS_SUCCESS != returnCode) {
            /* 异常结束数据库事务 */
            rglog.error("新增营销活动信息失败, RETURN_CODE=<{}>, MC_NO=<{}>", returnCode, globalMcNo);
            dbsUtil.dbsEndTransaction(false);
            throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
        }
    }

    /**
     * 将代理商分润类营销活动基本信息插入临时表中
     *
     * @param dbsUtil      数据库操作工具类
     * @param tmPlatBizTmp 业务数据临时表
     * @throws Exception 异常信息
     * @author Jinan Liu
     * @date 2020/5/22 15:39
     */
    private void insertTmpMoMcInfo(DbsUtil dbsUtil, TMPlatBizTmp tmPlatBizTmp) throws Exception {

        /* 数据入库 */
        PlatBizTmpMapper platBizTmpMapper = new PlatBizTmpMapperImpl();
        int returnCode = platBizTmpMapper.insertMcInfoByBank(tmPlatBizTmp);
        if (Database.DBS_SUCCESS != returnCode) {
            /* 异常结束数据库事务 */
            rglog.error("新增营销活动信息失败, RETURN_CODE=<{}>, MC_NO=<{}>", returnCode, globalMcNo);
            dbsUtil.dbsEndTransaction(false);
            throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
        }
    }

    /**
     * 代理商分润类营销活动信息表数据转换
     * 正式表数据转换为临时表数据
     *
     * @param mcAgentProfitSharingInfo 代理商分润类营销活动信息表
     * @return cc.rengu.igas.momp.common.entity.TMPlatBizTmp 业务数据临时表
     * @author Jinan Liu
     * @date 2020/5/22 11:49
     */
    private TMPlatBizTmp convertMoMcInfoToTmp(TMMcAgentProfitSharingInfo mcAgentProfitSharingInfo) {

        TMPlatBizTmp tmPlatBizTmp = new TMPlatBizTmp();

        try {
            /* 法人机构标识 */
            tmPlatBizTmp.setInstId(mcAgentProfitSharingInfo.getInstId());
            /* 营销活动编号 */
            tmPlatBizTmp.setMcNo(mcAgentProfitSharingInfo.getMcNo());
            /* 操作菜单 */
            tmPlatBizTmp.setOprMenuId(CommonConstant.DEFAULT_MENU_ID);
            /* 操作菜单名 */
            tmPlatBizTmp.setOprMenuName(CommonConstant.DEFAULT_MENU_NAME);
            /* 操作表中文名 */
            tmPlatBizTmp.setOprTableCname(TableNameEnum.T_M_MC_APS_INFO.getTableNameDesc());
            /* 操作表英文名 */
            tmPlatBizTmp.setOprTableEname(TableNameEnum.T_M_MC_APS_INFO.getTableNameCode());
            /* 操作 */
            tmPlatBizTmp.setBizOpr(BizOprEnum.INSERT.getBizOprCode());
            /* 数据域1 - 拼接JSON字符串 */
            tmPlatBizTmp.setBizData1(JsonOperation.packApsInfoTmpBizData1(mcAgentProfitSharingInfo, rglog));
            /* 状态 */
            tmPlatBizTmp.setBizStatus(BizStatusEnum.TMP_STATUS.getBizStatusCode());
            /* 营销活动状态 */
            tmPlatBizTmp.setMcStatus(McStatusEnum.DRAFT.getMcStatusCode());
            /* 审批状态 */
            tmPlatBizTmp.setAuditStatus(AuditStatusEnum.WAIT_FOR_SUBMIT.getAuditStatusCode());
            /* 创建人 */
            tmPlatBizTmp.setOprId(globalOprId);
            /* 创建时间 */
            tmPlatBizTmp.setCreateTime(globalTimeStamp);
            /* 代理商编号 */
            tmPlatBizTmp.setAgentMchntNo(mcAgentProfitSharingInfo.getAgentMchntNo());

            return tmPlatBizTmp;

        } catch (Exception e) {
            rglog.error("公共业务数据不可为空!");
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        }
    }

    /**
     * 插入营销活动机构信息表
     *
     * @param dbsUtil       数据库操作工具类
     * @param mcOrgInfoList 营销活动机构信息表
     * @throws Exception 异常信息
     * @author Jinan Liu
     * @date 2020/5/21 16:38
     */
    private void insertMcOrgInfo(DbsUtil dbsUtil, List<TMMcOrgInfo> mcOrgInfoList) throws Exception {

        McOrgInfoMapper mcOrgInfoMapper = new McOrgInfoMapperImpl();
        int returnCode = mcOrgInfoMapper.insertMcOrgInfoListByBank(mcOrgInfoList);
        if (Database.DBS_SUCCESS != returnCode) {
            /* 异常结束数据库事务 */
            rglog.error("新增营销活动机构信息失败, RETURN_CODE=<{}>, MC_NO=<{}>", returnCode, globalMcNo);
            dbsUtil.dbsEndTransaction(false);
            throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
        }
    }

    /**
     * 将营销活动机构信息插入临时表中
     *
     * @param dbsUtil          数据库操作工具类
     * @param tmPlatBizTmpList 业务数据临时表
     * @throws Exception 异常信息
     * @author Jinan Liu
     * @date 2020/5/28 22:17
     */
    private void insertMultiMcDetialInfoByBank(DbsUtil dbsUtil, List<TMPlatBizTmp> tmPlatBizTmpList) throws Exception {

        PlatBizTmpMapper platBizTmpMapper = new PlatBizTmpMapperImpl();
        int returnCode = platBizTmpMapper.insertMultiMcDetialInfoByBank(tmPlatBizTmpList);
        if (Database.DBS_SUCCESS != returnCode) {
            /* 异常结束数据库事务 */
            rglog.error("新增营销活动机构信息失败, RETURN_CODE=<{}>, MC_NO=<{}>", returnCode, globalMcNo);
            dbsUtil.dbsEndTransaction(false);
            throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
        }
    }

    /**
     * 营销活动机构信息表数据转换
     * 正式表数据转换为临时表数据
     *
     * @param tmMcOrgInfo 营销活动机构信息表
     * @return cc.rengu.igas.momp.common.entity.TMPlatBizTmp 业务数据临时表
     * @author Jinan Liu
     * @date 2020/5/28 22:12
     */
    private TMPlatBizTmp convertMcOrgInfoToTmp(TMMcOrgInfo tmMcOrgInfo) {

        TMPlatBizTmp tmPlatBizTmp = new TMPlatBizTmp();

        try {
            /* 法人机构标识 */
            tmPlatBizTmp.setInstId(tmMcOrgInfo.getInstId());
            /* 营销活动编号 */
            tmPlatBizTmp.setMcNo(tmMcOrgInfo.getMcNo());
            /* 机构编号 */
            tmPlatBizTmp.setOrgId(tmMcOrgInfo.getOrgId());
            /* 操作菜单 */
            tmPlatBizTmp.setOprMenuId(CommonConstant.DEFAULT_MENU_ID);
            /* 操作菜单名 */
            tmPlatBizTmp.setOprMenuName(CommonConstant.DEFAULT_MENU_NAME);
            /* 操作表中文名 */
            tmPlatBizTmp.setOprTableCname(TableNameEnum.T_M_MC_ORG_INFO.getTableNameDesc());
            /* 操作表英文名 */
            tmPlatBizTmp.setOprTableEname(TableNameEnum.T_M_MC_ORG_INFO.getTableNameCode());
            /* 操作 */
            tmPlatBizTmp.setBizOpr(BizOprEnum.INSERT.getBizOprCode());
            /* 数据域1 - 拼接JSON字符串 */
            tmPlatBizTmp.setBizData1(JsonOperation.packMcOrgInfoTmpBizData1(tmMcOrgInfo, rglog));
            /* 状态 */
            tmPlatBizTmp.setBizStatus(BizStatusEnum.TMP_STATUS.getBizStatusCode());
            /* 营销活动状态 */
            tmPlatBizTmp.setMcStatus(McStatusEnum.DRAFT.getMcStatusCode());
            /* 审批状态 */
            tmPlatBizTmp.setAuditStatus(AuditStatusEnum.WAIT_FOR_SUBMIT.getAuditStatusCode());
            /* 创建人 */
            tmPlatBizTmp.setOprId(globalOprId);
            /* 创建时间 */
            tmPlatBizTmp.setCreateTime(globalTimeStamp);

            return tmPlatBizTmp;

        } catch (Exception e) {
            rglog.error("公共业务数据不可为空!");
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        }
    }

    /**
     * 插入营销活动代理商分润类规则信息
     *
     * @param dbsUtil                          数据库操作工具类
     * @param mcAgentProfitSharingRuleInfoList 代理商分润类营销活动规则表
     * @throws Exception 异常信息
     * @author Jinan Liu
     * @date 2020/5/21 18:15
     */
    private void insertMcAgentProfitSharingRuleInfo(DbsUtil dbsUtil, List<TMMcAgentProfitSharingRuleInfo> mcAgentProfitSharingRuleInfoList) throws Exception {

        McRuleInfoMapper mcRuleInfoMapper = new McRuleInfoMapperImpl();
        int returnCode = mcRuleInfoMapper.insertAgentProfitSharingRuleInfoListByBank(globalInstId, mcAgentProfitSharingRuleInfoList);
        if (Database.DBS_SUCCESS != returnCode) {
            /* 异常结束数据库事务 */
            rglog.error("新增营销活动代理商分润类规则信息失败, RETURN_CODE=<{}>, MC_NO=<{}>", returnCode, globalMcNo);
            dbsUtil.dbsEndTransaction(false);
            throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
        }
    }

    /**
     * 营销活动规则信息表数据转换
     * 正式表数据转换为临时表数据
     *
     * @param tmMcAgentProfitSharingRuleInfo 代理商分润类营销活动规则表
     * @return cc.rengu.igas.momp.common.entity.TMPlatBizTmp 业务数据临时表
     * @author Jinan Liu
     * @date 2020/5/28 22:49
     */
    private TMPlatBizTmp convertMoMcRuleInfoToTmp(TMMcAgentProfitSharingRuleInfo tmMcAgentProfitSharingRuleInfo) {

        TMPlatBizTmp tmPlatBizTmp = new TMPlatBizTmp();

        try {
            /* 法人机构标识 */
            tmPlatBizTmp.setInstId(tmMcAgentProfitSharingRuleInfo.getInstId());
            /* 营销活动编号 */
            tmPlatBizTmp.setMcNo(tmMcAgentProfitSharingRuleInfo.getMcNo());
            /* 操作菜单 */
            tmPlatBizTmp.setOprMenuId(CommonConstant.DEFAULT_MENU_ID);
            /* 操作菜单名 */
            tmPlatBizTmp.setOprMenuName(CommonConstant.DEFAULT_MENU_NAME);
            /* 操作表中文名 */
            tmPlatBizTmp.setOprTableCname(TableNameEnum.T_M_MC_APS_RULE_INFO.getTableNameDesc());
            /* 操作表英文名 */
            tmPlatBizTmp.setOprTableEname(TableNameEnum.T_M_MC_APS_RULE_INFO.getTableNameCode());
            /* 操作 */
            tmPlatBizTmp.setBizOpr(BizOprEnum.INSERT.getBizOprCode());
            /* 数据域1 - 拼接JSON字符串 */
            tmPlatBizTmp.setBizData1(JsonOperation.packApsRuleInfoTmpBizData1(tmMcAgentProfitSharingRuleInfo, rglog));
            /* 状态 */
            tmPlatBizTmp.setBizStatus(BizStatusEnum.TMP_STATUS.getBizStatusCode());
            /* 营销活动状态 */
            tmPlatBizTmp.setMcStatus(McStatusEnum.DRAFT.getMcStatusCode());
            /* 审批状态 */
            tmPlatBizTmp.setAuditStatus(AuditStatusEnum.WAIT_FOR_SUBMIT.getAuditStatusCode());
            /* 创建人 */
            tmPlatBizTmp.setOprId(globalOprId);
            /* 创建时间 */
            tmPlatBizTmp.setCreateTime(globalTimeStamp);

            return tmPlatBizTmp;

        } catch (Exception e) {
            rglog.error("公共业务数据不可为空!");
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        }
    }

    /**
     * 删除代理商分润类营销活动基本信息
     *
     * @param dbsUtil 数据库操作工具类
     * @throws Exception 异常信息
     * @author Jinan Liu
     * @date 2020/5/21 16:35
     */
    private void deleteAgentProfitSharingMcInfo(DbsUtil dbsUtil) throws Exception {

        McDetailInfoMapper mcDetailInfoMapper = new McDetailInfoMapperImpl();
        int returnCode = mcDetailInfoMapper.deleteAgentProfitSharingMcInfo(globalInstId, globalMcNo);
        if (Database.DBS_SUCCESS != returnCode) {
            /* 异常结束数据库事务 */
            rglog.error("删除营销活动信息失败, RETURN_CODE=<{}>, INST_ID=<{}>, MC_NO=<{}>", returnCode, globalInstId, globalMcNo);
            dbsUtil.dbsEndTransaction(false);
            throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
        }
    }

    /**
     * 删除营销活动机构信息表
     *
     * @param dbsUtil 数据库操作工具类
     * @throws Exception 异常信息
     * @author Jinan Liu
     * @date 2020/5/21 16:38
     */
    private void deleteMcOrgInfo(DbsUtil dbsUtil) throws Exception {

        McOrgInfoMapper mcOrgInfoMapper = new McOrgInfoMapperImpl();
        int returnCode = mcOrgInfoMapper.deleteMcOrgInfoListByBank(globalInstId, globalMcNo);
        if (Database.DBS_SUCCESS != returnCode) {
            /* 异常结束数据库事务 */
            rglog.error("删除营销活动机构信息失败, RETURN_CODE=<{}>, INST_ID=<{}>, MC_NO=<{}>", returnCode, globalInstId, globalMcNo);
            dbsUtil.dbsEndTransaction(false);
            throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
        }
    }

    /**
     * 删除营销活动代理商分润类规则信息
     *
     * @param dbsUtil 数据库操作工具类
     * @throws Exception 异常信息
     * @author Jinan Liu
     * @date 2020/5/21 18:15
     */
    private void deleteAgentProfitSharingRuleInfo(DbsUtil dbsUtil) throws Exception {

        McRuleInfoMapper mcRuleInfoMapper = new McRuleInfoMapperImpl();
        int returnCode = mcRuleInfoMapper.deleteAgentProfitSharingRuleInfoByPrimaryKey(globalInstId, globalMcNo, null);
        if (Database.DBS_SUCCESS != returnCode) {
            /* 异常结束数据库事务 */
            rglog.error("删除营销活动代理商分润类规则信息失败, RETURN_CODE=<{}>, INST_ID=<{}>, MC_NO=<{}>", returnCode, globalInstId, globalMcNo);
            dbsUtil.dbsEndTransaction(false);
            throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
        }
    }

    /**
     * 删除指定营销活动编号的所有草稿状态的数据数据
     *
     * @param dbsUtil      数据库操作工具类
     * @param tmPlatBizTmp 业务数据临时表
     * @throws Exception 异常信息
     * @author Jinan Liu
     * @date 2020/5/28 23:12
     */
    private void deleteAllDraftMcInfoByBank(DbsUtil dbsUtil, TMPlatBizTmp tmPlatBizTmp) throws Exception {

        PlatBizTmpMapper platBizTmpMapper = new PlatBizTmpMapperImpl();
        int returnCode = platBizTmpMapper.deleteAllDraftMcInfoByBank(tmPlatBizTmp);
        if (Database.DBS_SUCCESS != returnCode) {
            /* 异常结束数据库事务 */
            rglog.error("删除草稿状态营销活动临时表数据失败, RETURN_CODE=<{}>, INST_ID=<{}>, MC_NO=<{}>", returnCode, globalInstId, globalMcNo);
            dbsUtil.dbsEndTransaction(false);
            throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
        }
    }

    /**
     * 保存数据流程
     *
     * @param xmlTreeUtil                           内部XML树
     * @param editAgentProfitSharingMcDetailRequest 代理商分润营销活动信息编辑接口请求对象
     * @throws Exception 异常信息
     * @author liujinan
     * @since 2020-07-01 18:50
     */
    private void saveAllMcInfoByBank(XmlTreeUtil xmlTreeUtil, EditAgentProfitSharingMcDetailRequest editAgentProfitSharingMcDetailRequest) throws Exception {

        int returnCode;
        /* 营销活动信息正式表查询 */
        McDetailInfoMapper mcDetailInfoMapper = new McDetailInfoMapperImpl();
        TMMcAgentProfitSharingInfo tmMcAgentProfitSharingInfo = (TMMcAgentProfitSharingInfo) mcDetailInfoMapper.selectMcDetailInfo(globalInstId, globalMcNo, TABLE_NAME);
        if (null == tmMcAgentProfitSharingInfo) {
            rglog.error("法人机构<{}>的营销活动<{}>的信息不存在!");
            throw new BizException(RespCodeEnum.GET_AGENT_PROFIT_SHARING_MC_DETAIL_ERROR.getRespCode(), RespCodeEnum.GET_AGENT_PROFIT_SHARING_MC_DETAIL_ERROR.getRespDesc());
        }

        /* 营销活动信息临时表查询 */
        PlatBizTmpMapper platBizTmpMapper = new PlatBizTmpMapperImpl();
        TMPlatBizTmp tmPlatBizTmp = platBizTmpMapper.selectTmpMcInfo(globalInstId, globalMcNo, TABLE_NAME);
        if (null == tmPlatBizTmp) {
            rglog.error("法人机构<{}>的营销活动<{}>的信息不存在!");
            throw new BizException(RespCodeEnum.GET_AGENT_PROFIT_SHARING_MC_DETAIL_ERROR.getRespCode(), RespCodeEnum.GET_AGENT_PROFIT_SHARING_MC_DETAIL_ERROR.getRespDesc());
        }

        /* 数据库有历史数据,需要判断历史数据状态 */
        /* 判断营销活动审批状态 */
        if (!AuditStatusEnum.WAIT_FOR_SUBMIT.getAuditStatusCode().equals(tmPlatBizTmp.getAuditStatus()) &&
                !AuditStatusEnum.NEW_AUDIT_REJECT.getAuditStatusCode().equals(tmPlatBizTmp.getAuditStatus()) &&
                !AuditStatusEnum.MODIFY_AUDIT_REJECT.getAuditStatusCode().equals(tmPlatBizTmp.getAuditStatus()) &&
                !AuditStatusEnum.PUBLISH_AUDIT_REJECT.getAuditStatusCode().equals(tmPlatBizTmp.getAuditStatus())) {
            /* 营销活动审批状态异常,不可保存数据 */
            rglog.error("法人机构<{}>的营销活动<{}>的审批状态<{}>异常,不可保存数据!", globalInstId, globalMcNo, tmPlatBizTmp.getAuditStatus());
            throw new BizException(RespCodeEnum.WRONG_AUDIT_STATUS_TO_SAVE_ERROR.getRespCode(), RespCodeEnum.WRONG_AUDIT_STATUS_TO_SAVE_ERROR.getRespDesc());
        }

        String auditStatus = tmMcAgentProfitSharingInfo.getAuditStatus();
        String mcStatus = tmMcAgentProfitSharingInfo.getMcStatus();

        /* 开启数据库事务 */
        String dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(AppConfigConstant.DATABASE_CONF_NODE, AppConfigConstant.MOMP_POOL_NAME);
        String corporation = xmlTreeUtil.getXmlTreeStringValue(AppParamConstant.CORPORATION);
        if (null != corporation && !corporation.isEmpty()) {
            String dbPoolCashNode = corporation.trim() + AppParamConstant.DATABASE_CONF_NODE;
            dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(dbPoolCashNode, AppConfigConstant.MOMP_POOL_NAME);
        }
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        dbsUtil.dbsBeginTransaction();

        if (McStatusEnum.PROGRESSING.getMcStatusCode().equals(mcStatus)) {
            /* 正式表营销活动状态是进行中,不允许保存草稿 */
            dbsUtil.dbsEndTransaction(false);
            rglog.error("法人机构<{}>的营销活动<{}>的营销活动状态<{}>异常,不可保存数据!", globalInstId, globalMcNo, tmPlatBizTmp.getAuditStatus());
            throw new BizException(RespCodeEnum.WRONG_MC_STATUS_TO_SAVE_ERROR.getRespCode(), RespCodeEnum.WRONG_MC_STATUS_TO_SAVE_ERROR.getRespDesc());
        } else {
            /* 正式表营销活动状态不是进行中,正式表临时表一起更新,先删除原数据再插入 */
            updateMcInfoByBank(dbsUtil, editAgentProfitSharingMcDetailRequest);

            /* 更新临时表审批状态 */
            returnCode = platBizTmpMapper.updateTmpMcInfoByMcNoAndAuditStatus(globalInstId, globalMcNo, tmPlatBizTmp,
                    AuditStatusEnum.WAIT_FOR_SUBMIT.getAuditStatusCode(), globalOprId, globalTimeStamp);
            if (Database.DBS_SUCCESS != returnCode) {
                /* 更新临时表中营销活动审批状态失败 */
                dbsUtil.dbsEndTransaction(false);
                rglog.error("更新临时表中营销活动审批状态失败, RETURN_CODE=<{}>, MC_NO=<{}>", returnCode, globalMcNo);
                throw new BizException(RespCodeEnum.UPDATE_TMP_MC_STATUS_FAILED_ERROR.getRespCode(), RespCodeEnum.UPDATE_TMP_MC_STATUS_FAILED_ERROR.getRespDesc());
            }

            /* 更新正式表审批状态 */
            TMMcAgentProfitSharingInfo tmMcAgentProfitSharingInfo1 = new TMMcAgentProfitSharingInfo();
            tmMcAgentProfitSharingInfo1.setInstId(globalInstId);
            tmMcAgentProfitSharingInfo1.setMcNo(globalMcNo);
            tmMcAgentProfitSharingInfo1.setMcStatus(mcStatus);
            tmMcAgentProfitSharingInfo1.setAuditStatus(auditStatus);
            tmMcAgentProfitSharingInfo1.setLastOprId(globalOprId);
            tmMcAgentProfitSharingInfo1.setUpdateTime(globalTimeStamp);

            returnCode = mcDetailInfoMapper.updateMcStatusForPublishing(tmMcAgentProfitSharingInfo1, TABLE_NAME);
            if (Database.DBS_SUCCESS != returnCode) {
                /* 更新正式表中营销活动审批状态失败 */
                dbsUtil.dbsEndTransaction(false);
                rglog.error("更新正式表中营销活动审批状态失败, RETURN_CODE=<{}>, MC_NO=<{}>", returnCode, globalMcNo);
                throw new BizException(RespCodeEnum.UPDATE_MC_STATUS_FAILED_ERROR.getRespCode(), RespCodeEnum.UPDATE_MC_STATUS_FAILED_ERROR.getRespDesc());
            }
        }

        /* 正常结束数据库事务 */
        dbsUtil.dbsEndTransaction(true);
    }

    /**
     * 更新营销活动信息
     * 进行保存的时候使用(可能是草稿的保存,也可能是被拒绝的再次修改后的保存)
     *
     * @param editAgentProfitSharingMcDetailRequest 代理商分润类营销活动信息编辑接口请求对象
     * @throws Exception 异常信息
     * @author liujinan
     * @date 2020/7/2 00:13
     */
    private void updateMcInfoByBank(DbsUtil dbsUtil, EditAgentProfitSharingMcDetailRequest editAgentProfitSharingMcDetailRequest) throws Exception {

        //删除指定营销活动编号的所有草稿状态的数据
        PlatBizTmpMapper platBizTmpMapper = new PlatBizTmpMapperImpl();
        int returnCode = platBizTmpMapper.deleteTmpMcDataByMcNo(globalInstId, globalMcNo);
        if (Database.DBS_SUCCESS != returnCode) {
            /* 删除临时表数据失败 */
            dbsUtil.dbsEndTransaction(false);
            rglog.error("删除临时表中营销活动各信息失败, RETURN_CODE=<{}>, MC_NO=<{}>", returnCode, globalMcNo);
            throw new BizException(RespCodeEnum.DELETE_TMP_MC_DATA_ERROR.getRespCode(), RespCodeEnum.DELETE_TMP_MC_DATA_ERROR.getRespDesc());
        }
        //删除正式表数据
        deleteAgentProfitSharingMcInfo(dbsUtil);
        deleteMcOrgInfo(dbsUtil);
        deleteAgentProfitSharingRuleInfo(dbsUtil);

        //重新插入正式表和临时表数据
        insertAllMcInfoByBank(dbsUtil, editAgentProfitSharingMcDetailRequest);
    }

    /**
     * 校验接口上送的机构信息和代理商所属机构是否匹配
     *
     * @throws Exception 异常信息
     * @author liujinan
     * @date 2020/7/14 14:00
     */
    private void checkAgentAndOrgInfo(EditAgentProfitSharingMcDetailRequest editAgentProfitSharingMcDetailRequest) throws Exception {

        String traceNo = editAgentProfitSharingMcDetailRequest.getHeader().getTraceNo();

        List<McOrgInfoBean> mcOrgInfoBeanList = editAgentProfitSharingMcDetailRequest.getOrgInfoObj();
        //按照机构层级排序,取排序后的最后一个
        mcOrgInfoBeanList.sort(Comparator.comparingInt(mcOrgInfoBean -> Integer.parseInt(mcOrgInfoBean.getOrgHierarchy())));

        String requestAgentOrgId = mcOrgInfoBeanList.get(mcOrgInfoBeanList.size() - 1).getOrgId();

        //接口请求上送的代理商编号
        String agentNo = editAgentProfitSharingMcDetailRequest.getMcInfoObj().getAgentMchntNo();
        McDetailInfoMapper mcDetailInfoMapper = new McDetailInfoMapperImpl();
        //查询代理商参与的活动
        List<TMMcAgentProfitSharingInfo> tmMcAgentProfitSharingInfoList = mcDetailInfoMapper.selectApsMcInfoList(globalInstId, agentNo, editAgentProfitSharingMcDetailRequest.getMcInfoObj().getMcStartDate());
        //如果list不为空或条数大于0，抛出
        if (null != tmMcAgentProfitSharingInfoList && tmMcAgentProfitSharingInfoList.size() > 0) {
            rglog.info("该代理商已参加进行中的代理商分润活动，不允许再次创建活动");
            throw new BizException(RespCodeEnum.WRONG_AGENT_ISALREADY_ORTHER_INMC_ERROR.getRespCode(), RespCodeEnum.WRONG_AGENT_ISALREADY_ORTHER_INMC_ERROR.getRespDesc());
        }

        TBAgentInfoMapper tbAgentInfoMapper = new TBAgentInfoMapperImpl();

        rglog.info("交易流水号：<{}>, 查询代理商<{}>代理商信息开始...", traceNo, agentNo);
        TBAgentInfo TBAgentInfo = tbAgentInfoMapper.selectAgentInfoByPrimaryKey(globalInstId, agentNo);
        if (null == TBAgentInfo) {
            rglog.error("交易流水号：<{}>, 查询代理商<{}>代理商信息失败", traceNo, agentNo);
            throw new BizException(RespCodeEnum.GET_AGENT_INFO_ERROR.getRespCode(), RespCodeEnum.GET_AGENT_INFO_ERROR.getRespDesc());
        }
        //上送的代理商实际所属的机构
        String realAgentOrgId = TBAgentInfo.getManageInstId();

        if (!requestAgentOrgId.equals(realAgentOrgId)) {
            rglog.error("交易流水号：<{}>, 接口上送的机构信息与代理商<{}>实际所属机构不匹配！", traceNo, agentNo);
            throw new BizException(RespCodeEnum.CHECK_AGENTREALORG_REQUESTORG_FAIL.getRespCode(), RespCodeEnum.CHECK_AGENTREALORG_REQUESTORG_FAIL.getRespDesc());
        }
        rglog.info("交易流水号：<{}>, 上送的机构信息与代理商<{}>实际所属机构校验通过", traceNo, agentNo);

        /* 接口上送的机构信息中不包含当前机构所属的上级机构，所以需要把上属机构补充道机构信息表中*/
        //需要从接口上送的机构信息中添加的上级机构
        List<McOrgInfoBean> addOrgIdList = new ArrayList<>();
        //最终机构信息（补充完上级机构后的机构列表）
        List<McOrgInfoBean> requestResultOrgList = editAgentProfitSharingMcDetailRequest.getOrgInfoObj();

        String queryOrgId = editAgentProfitSharingMcDetailRequest.getQueryOrgId();
        //查询当前登录用户的所属机构信息
        OrganizationMapper organizationMapper = new OrganizationMapperImpl();
        Organization queryOrgInfo = organizationMapper.selectOrganization(globalInstId, queryOrgId);
        //当前登录用户所属机构的最大深度
        int orgLevealDepth = 6;
        Boolean superOrgFlag = false;
        while (orgLevealDepth > 0) {
            if (null != queryOrgInfo) {
                if (superOrgFlag) {
                    McOrgInfoBean mcOrgInfoBean = new McOrgInfoBean();
                    mcOrgInfoBean.setOrgHierarchy(queryOrgInfo.getOrgLevel());
                    mcOrgInfoBean.setOrgId(queryOrgInfo.getOrgCode());
                    mcOrgInfoBean.setOrgName(queryOrgInfo.getOrgName());
                    mcOrgInfoBean.setOprType(CommonConstant.DEFAULT_OPR_ID);
                    addOrgIdList.add(mcOrgInfoBean);
                }
                String superOrgId = queryOrgInfo.getSuperOrgCode();
                String orgLevel = queryOrgInfo.getOrgLevel();
                rglog.info("交易流水号：<{}>,当前机构机构编码<{}>,上级机构编码<{}>,机构编码级别<{}>", traceNo, queryOrgInfo.getOrgCode(), superOrgId, orgLevel);

                if (null != superOrgId && !"00".equals(orgLevel)) {
                    rglog.info("交易流水号：<{}>,接口请求上送的机构信息中需要添加 <{}>!", traceNo, superOrgId);
                    queryOrgInfo = organizationMapper.selectOrganization(globalInstId, superOrgId);
                    superOrgFlag = true;
                } else
                    break;
                orgLevealDepth--;
            } else {
                rglog.error("交易流水号：<{}>, 机构<{}>机构信息查询失败！", traceNo, addOrgIdList.size(), queryOrgId);
                throw new BizException(RespCodeEnum.NO_ORG_INFO_ERROR.getRespCode(), RespCodeEnum.NO_ORG_INFO_ERROR.getRespDesc());
            }
        }

        if (null != addOrgIdList && !addOrgIdList.isEmpty()) {
            rglog.info("交易流水号：<{}>, 接口上送的机构机构信息中有需要添加<{}>个上级机构信息", traceNo, addOrgIdList.size());
            requestResultOrgList.addAll(addOrgIdList);
            editAgentProfitSharingMcDetailRequest.setOrgInfoObj(requestResultOrgList);
        } else {
            rglog.info("交易流水号：<{}>, 接口上送的机构机构信息中不需要添加上级机构信息（当前用户所属机构已经为总行级别）", traceNo, addOrgIdList.size());
        }
    }

    /**
     * 检查 上送 活动信息 金额字段不能为负数
     *
     * @param agentProfitSharingMcInfoBean
     * @author ls
     * @date 2020/10/21
     */
    private void checkMcInfoObjFieldHasNegativeNumber(AgentProfitSharingMcInfoBean agentProfitSharingMcInfoBean) {
        /* 活动预算 */
        if (!StringUtil.isNullorEmpty(agentProfitSharingMcInfoBean.getBudget()) && new BigDecimal(agentProfitSharingMcInfoBean.getBudget()).compareTo(zero) < 0) {
            throw new BizException(RespCodeEnum.FIELD_HAS_NEGATIVE_NUMBER.getRespCode(), RespCodeEnum.FIELD_HAS_NEGATIVE_NUMBER.getRespDesc());
        }
        /* 有效交易达标金额 */
        if (!StringUtil.isNullorEmpty(agentProfitSharingMcInfoBean.getCriteriaLimit()) && new BigDecimal(agentProfitSharingMcInfoBean.getCriteriaLimit()).compareTo(zero) < 0) {
            throw new BizException(RespCodeEnum.FIELD_HAS_NEGATIVE_NUMBER.getRespCode(), RespCodeEnum.FIELD_HAS_NEGATIVE_NUMBER.getRespDesc());
        }
        /* 新商户达标交易金额 */
        if (!StringUtil.isNullorEmpty(agentProfitSharingMcInfoBean.getCriteriaAmount()) && new BigDecimal(agentProfitSharingMcInfoBean.getCriteriaAmount()).compareTo(zero) < 0) {
            throw new BizException(RespCodeEnum.FIELD_HAS_NEGATIVE_NUMBER.getRespCode(), RespCodeEnum.FIELD_HAS_NEGATIVE_NUMBER.getRespDesc());
        }
        /* 新商户达标交易笔数 */
        if (!StringUtil.isNullorEmpty(agentProfitSharingMcInfoBean.getCriteriaQuantity()) && new BigDecimal(agentProfitSharingMcInfoBean.getCriteriaQuantity()).compareTo(zero) < 0) {
            throw new BizException(RespCodeEnum.FIELD_HAS_NEGATIVE_NUMBER.getRespCode(), RespCodeEnum.FIELD_HAS_NEGATIVE_NUMBER.getRespDesc());
        }
    }

    /**
     * 检查 上送 活动规则信息数据 金额字段不能为负数
     *
     * @param agentProfitSharingRuleInfoBean
     * @author ls
     * @date 2020/10/21
     */
    private void checkRuleInfoFieldHasNegativeNumber(AgentProfitSharingRuleInfoBean agentProfitSharingRuleInfoBean) {
        /* 控制下限 */
        if (!StringUtil.isNullorEmpty(agentProfitSharingRuleInfoBean.getCriteriaFloor()) && new BigDecimal(agentProfitSharingRuleInfoBean.getCriteriaFloor()).compareTo(zero) < 0) {
            throw new BizException(RespCodeEnum.FIELD_HAS_NEGATIVE_NUMBER.getRespCode(), RespCodeEnum.FIELD_HAS_NEGATIVE_NUMBER.getRespDesc());
        }
        /* 控制上限 */
        if (!StringUtil.isNullorEmpty(agentProfitSharingRuleInfoBean.getCriteriaCelling()) && new BigDecimal(agentProfitSharingRuleInfoBean.getCriteriaCelling()).compareTo(zero) < 0) {
            throw new BizException(RespCodeEnum.FIELD_HAS_NEGATIVE_NUMBER.getRespCode(), RespCodeEnum.FIELD_HAS_NEGATIVE_NUMBER.getRespDesc());
        }
    }


}
